package com.hankol.newretail.viewmodel

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.View
import android.view.animation.*
import android.widget.RelativeLayout
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import com.baselibrary.Constants
import com.baselibrary.base.BasicListBean
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.SharePosterBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.net.APIResponse
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.AmountUtil
import com.baselibrary.utils.GsonUtils
import com.baselibrary.view.AutoScrollRecyclerView
import com.hankol.newretail.R
import com.hankol.newretail.adapter.details.GoodsCoverVpAdapter
import com.hankol.newretail.adapter.details.GoodsDetailAdapter
import com.hankol.newretail.adapter.details.GoodsSpecAdapter
import com.hankol.newretail.bean.EvaluationBean
import com.hankol.newretail.bean.GoodListBean
import com.hankol.newretail.bean.ShopCartAddBean
import com.hankol.newretail.bean.ShopCartNumData
import com.hankol.newretail.bean.goods_details.*
import com.hankol.newretail.databinding.ActivityGoodsDetailNewBinding
import com.hankol.newretail.respository.NewReatilRequestManager
import com.hankol.newretail.utils.SingleLiveData
import com.hankol.newretail.widget.GoodsVideoView
import com.tencent.rtmp.TXVodPlayer
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import org.json.JSONObject
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.ArrayList

/**
 * @author: 关忆北、
 * @date: 2022/8/4
 * @Des：
 */
class GoodsDetailViewModel : BaseViewModel() {
    var mAutoTask: Disposable? = null
    var mSmoothScrollPos: Int = 0
    var mLastSmoothScrollPos: Int = -1
    var mSmoothScroll: LinearSmoothScroller? = null
    val specValueMap: LinkedHashMap<String, String> = linkedMapOf()//存 578:蓝色 | 579:黑色 | 580:l | 582:xxl

    val seckillSpuDetailSkuMap: LinkedHashMap<String, SeckillSpuDetailSkuMapData> = linkedMapOf()

    var specRenderList: LinkedHashMap<String, ArrayList<String>> = linkedMapOf()//存 171->578 579| 172->580、582

    var specRelationMap: LinkedHashMap<String, ArrayList<String>> = linkedMapOf()//有库存的

    var specNameMap: LinkedHashMap<String, String> = linkedMapOf()//存 171:颜色 172:规格
    val nameList: ArrayList<String> = arrayListOf()//存 171 | 172


    var defSelectedSkuList: ArrayList<Spec> = arrayListOf()//默认选中的规格

    val normsIndexOf: LinkedHashMap<String, MallSkuDto> = linkedMapOf()//记录规格索引

    val goodsDetailsLD: MutableLiveData<GoodsDetails> = MutableLiveData()
    val goodsRecommendLD: MutableLiveData<BasicListBean<GoodListBean>> = MutableLiveData()
    val goodsGiftLD: MutableLiveData<GoodsGiftBean> = MutableLiveData()
    val goodsGrassShow: MutableLiveData<BasicListBean<GrassShowBean>> = MutableLiveData()
    val goodsEvaluationLD: MutableLiveData<BasicListBean<EvaluationBean>> = MutableLiveData()
    var addCartShopLD: SingleLiveData<ShopCartAddBean> = SingleLiveData()
    var shopCartNumLD: MutableLiveData<ShopCartNumData> = MutableLiveData()
    var fansApplyLD: MutableLiveData<Any> = MutableLiveData()

    fun reqAddCartShop(skuid: Long, num: Int) {
        NewReatilRequestManager.getInstance().reqAddCartShop(1, skuid, num, addCartShopLD)
    }

    fun upHoverLocation(goodsVideoView: GoodsVideoView, topMargin: Int) {
        val params: RelativeLayout.LayoutParams = goodsVideoView.layoutParams as RelativeLayout.LayoutParams
        params.topMargin = topMargin
        goodsVideoView.layoutParams = params
    }

    fun reqGoodsDetails(spuId: Long, skuId: Long) {
        NewReatilRequestManager.getInstance().reqGoodsDetails(goodsDetailsLD, spuId, skuId)
    }

    fun reqGoodsDetails(spuId: Long, skuId: Long, apiResponse: APIResponse<GoodsDetails>) {
        NewReatilRequestManager.getInstance().reqGoodsDetails(apiResponse, spuId, skuId)
    }

    fun reqGoodsRecommend(ids: String, type: Int, shopId: Int, page: Int) {
        NewReatilRequestManager.getInstance().reqRecommendGoods(goodsRecommendLD, ids, type, shopId, page, Int.MAX_VALUE)
    }

    fun reqGoodsGrassShow(spuId: Long, page: Int) {
        NewReatilRequestManager.getInstance().reqGoodsDetailsGrassShow(goodsGrassShow, spuId, page, 20)
    }

    fun reqGoodsGiftData(skuId: Int, spuId: Int) {
        NewReatilRequestManager.getInstance().reqGoodsDetailsGiftData(goodsGiftLD, skuId, spuId)
    }

    fun reqGoodsEvaluation(spuId: Long, page: Int) {
        NewReatilRequestManager.getInstance().reqGoodsEvaluation(goodsEvaluationLD, spuId, page, 20)
    }

    //申请详情 判断是否申请粉丝
    fun reqFansApplyDetail() {
        NewReatilRequestManager.getInstance().reqFansApplyDetail(fansApplyLD)
    }

    //购物车商品数量
    fun reqShopCartNum() {
        NewReatilRequestManager.getInstance().reqShopCartNum(shopCartNumLD)
    }

    fun analysisJson(jString: String) {
        val jsonObject = JSONObject(jString)
        val specExtData: JSONObject = jsonObject.getJSONObject("data").getJSONObject("specExtData");
        val seckillActSkuStockMapData: JSONObject = jsonObject.getJSONObject("data").getJSONObject("seckillSpuDetailSkuMap")
        if (seckillActSkuStockMapData!=null){
            val keys = seckillActSkuStockMapData.keys()
            while (keys.hasNext()) {
                val nextId = keys.next()
                val str = seckillActSkuStockMapData.getString(nextId)
                this.seckillSpuDetailSkuMap[nextId] = GsonUtils.parseJsonToBean(str,SeckillSpuDetailSkuMapData::class.java)
            }
        }
        val mapNormsGroupJSON = specExtData.getJSONArray("specRenderList");
        val length = mapNormsGroupJSON.length()
        for (index in 0 until length) {
            val jsonObject1 = mapNormsGroupJSON.getJSONObject(index)
            val keys: Iterator<String> = jsonObject1.keys()
            while (keys.hasNext()) {
                val keysId = keys.next() // specRenderList 中的 171
                val stockNormsGroupArray = jsonObject1.getJSONArray(keysId)
                val list: ArrayList<String> = arrayListOf()
                for (index1 in 0 until stockNormsGroupArray.length()) {
                    list.add(stockNormsGroupArray[index1].toString())
                }
                nameList.add(keysId)
                specRenderList[keysId] = list
            }
        }

        val specNameMap = specExtData.getJSONObject("specNameMap");
        val keys = specNameMap.keys()
        while (keys.hasNext()) {
            val nextId = keys.next()
            val str = specNameMap.getString(nextId)
            this.specNameMap[nextId] = str
        }
        val specValueMap = specExtData.getJSONObject("specValueMap");
        val specValueKeys = specValueMap.keys()
        while (specValueKeys.hasNext()) {
            val nextId = specValueKeys.next()
            val str = specValueMap.getString(nextId)
            this.specValueMap[nextId] = str
        }

        val specRelationMap = specExtData.getJSONObject("specRelationMap");
        val specRelationId = specRelationMap.keys()
        while (specRelationId.hasNext()) {
            val keyId = specRelationId.next()
            val arrayValue = specRelationMap.getJSONArray(keyId)
            val list: ArrayList<String> = arrayListOf()
            for (index1 in 0 until arrayValue.length()) {
                list.add(arrayValue[index1].toString())
            }
            this.specRelationMap[keyId] = list
        }

    }

    fun assembleNormsIndex(result: GoodsDetails) {
        val mallSkuDtoList = result.mallSkuDtoList
        for (index in mallSkuDtoList.indices) {
            val specList = mallSkuDtoList[index].specList
            val buffer: StringBuffer = StringBuffer()
            specList.forEach { it ->
                buffer.append(it.nameId).append(it.valueId)
            }
            normsIndexOf[buffer.toString()] = mallSkuDtoList[index]
        }
    }


    fun getDefSelectedSku(result: GoodsDetails): ArrayList<Spec> {
        result.mallSkuDtoList.forEach {
            if (it.selectByDef == 1) {
                return it.specList
            }
        }
        return ArrayList()
    }

    fun getDefSku(result: GoodsDetails): Long {
        result.mallSkuDtoList.forEach {
            if (it.selectByDef == 1) {
                return it.id
            }
        }
        return 0
    }

    fun getSkuBean(mNormsGroupAdapter: GoodsSpecAdapter): MallSkuDto? {
        val buffer = StringBuffer()
        for (d in mNormsGroupAdapter.data) {
            buffer.append(d.groupId).append(d.defaultSku.valueId)
        }
        return if (normsIndexOf.containsKey(buffer.toString())) {
            normsIndexOf[buffer.toString()]
        } else {
            null
        }
    }


    fun initAuto(context: Context) {
        mSmoothScroll = object : LinearSmoothScroller(context) {
            override fun getVerticalSnapPreference(): Int {
                return LinearSmoothScroller.SNAP_TO_START
            }

            override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
                // 移动一英寸需要花费3ms
                return 3f / (displayMetrics?.density ?: 1f)
            }

        }
    }

    fun startAuto(autoScroll: AutoScrollRecyclerView) {
        (autoScroll.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(mSmoothScrollPos, 0)
        if (mAutoTask != null && mAutoTask?.isDisposed == false) mAutoTask?.dispose()

        val times = Random().nextInt(5) + 4

        mAutoTask = Observable.interval(times.toLong(), TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            mSmoothScroll?.let { mSmoothScroll ->
                //界面上滑后，mSmoothScroll.targetPosition会根据mSmoothScrollPos改变，界面一直在显示时  mSmoothScroll.targetPosition = -1
                mSmoothScrollPos++
                mSmoothScroll.targetPosition = mSmoothScrollPos
                (autoScroll.layoutManager as LinearLayoutManager).startSmoothScroll(mSmoothScroll)
            }
        }
    }

    fun stopAuto() {
        if (mAutoTask != null) {
            mAutoTask?.dispose()
        }
    }

    fun showShowyView(binding: ActivityGoodsDetailNewBinding, commonVodPlayer: TXVodPlayer, coverVpAdapter: GoodsCoverVpAdapter?) {
        if (isPaying(coverVpAdapter)) {
            //结束视频封面图的播放
            if (binding.gvvDetailsVideoHover.visibility != View.VISIBLE) {
                binding.gvvDetailsVideoHover.visibility = View.VISIBLE
                binding.gvvDetailsVideoHover.mVodPlayer = commonVodPlayer
                commonVodPlayer.setPlayerView(binding.gvvDetailsVideoHover.mTxclGoodsDetVideo)
                binding.gvvDetailsVideoHover.setPlayMode(3)
                coverVpAdapter?.let {
                    it.goodsVideoView?.stopPlay()
                    //把弹窗播放的需要变化的view传递给封面图播放的view
                    it.goodsVideoView?.mSbGoodsDetVoice = binding.gvvDetailsVideoHover.mSbGoodsDetVoice
                    it.goodsVideoView?.setOnPlayCompleteCallBack {
                        hideShowyView(binding, commonVodPlayer, coverVpAdapter, true)
                    }
                }
                commonVodPlayer.resume()
            }
        }


    }


    fun hideShowyView(binding: ActivityGoodsDetailNewBinding, commonVodPlayer: TXVodPlayer, coverVpAdapter: GoodsCoverVpAdapter?, isEnd: Boolean) {
        coverVpAdapter?.let {
            if (binding.gvvDetailsVideoHover.visibility == View.VISIBLE) {
                binding.gvvDetailsVideoHover.stopPlay()
                commonVodPlayer.setPlayerView(it.goodsVideoView?.mTxclGoodsDetVideo)
                //先将进度条赋值为原始值，再将弹窗的进度条交给原始值
                it.goodsVideoView?.mSbGoodsDetVoice = it.goodsVideoView?.originalSbGoodsDetVoice
                it.goodsVideoView?.visibilityCover()
                if (!isEnd) {
                    commonVodPlayer.resume()
                }
                binding.gvvDetailsVideoHover.visibility = View.GONE
            } else {

            }

        }

    }

    fun getDefPrice(goodsDetailBean: GoodsDetails): Long {
        if (goodsDetailBean.hasSelectSpec) {
            return goodsDetailBean.selectedPrice
        } else {
            val mallSkuDtoList = goodsDetailBean.mallSkuDtoList
            if (mallSkuDtoList.checkNotNull()) {
                mallSkuDtoList.forEach {
                    if (it.selectByDef == 1) {
                        return it.showPrice
                    }
                }
                return mallSkuDtoList[0].showPrice
            }
        }
        return 0L
    }

    fun getDefSeckillPrice(goodsDetailBean: GoodsDetails): Long {
        if (goodsDetailBean.hasSelectSpec) {
            return goodsDetailBean.selectedSeckillPrice
        } else {
            return goodsDetailBean.seckillActProductExtDTO?.price!!.toLong()
        }
        return 0L
    }

    fun getDefSeckillFansPrice(goodsDetailBean: GoodsDetails): Long {
        if (goodsDetailBean.hasSelectSpec) {
            return goodsDetailBean.selectedSeckillFansPrice
        } else {
            return goodsDetailBean.seckillActProductExtDTO?.fansPrice!!.toLong()
        }
        return 0L
    }

    fun getDefFansPrice(goodsDetailBean: GoodsDetails): Long {
        if (goodsDetailBean.hasSelectSpec) {
            return goodsDetailBean.selectedFansPrice
        } else {
            val mallSkuDtoList = goodsDetailBean.mallSkuDtoList
            if (mallSkuDtoList.checkNotNull()) {
                mallSkuDtoList.forEach {
                    if (it.selectByDef == 1) {
                        return it.showFansPrice
                    }
                }
                return mallSkuDtoList[0].showFansPrice
            }
        }
        return 0L
    }

    fun goodsPosterShare(activity: Activity, goodsDetailBean: GoodsDetails, url: String) {
        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
            override fun permissionsPass() {
                val sharePosterBean = SharePosterBean(9)//SHARE_TYPE_GOOD
                sharePosterBean.shareImage = goodsDetailBean.covers[0]
                sharePosterBean.shareContent = goodsDetailBean.name
                sharePosterBean.sharePrice = AmountUtil.changeF2Y("${getDefFansPrice(goodsDetailBean)}").toString()
                sharePosterBean.shareUrl = url
                sharePosterBean.shareQrCodeUrl = goodsDetailBean.shareWxAppQrImgUrl.checkValue()
                sharePosterBean.goodsId = goodsDetailBean.spuId.toString()
                sharePosterBean.shopName = if (goodsDetailBean.shopInfo == null) "酣客总社" else goodsDetailBean.shopInfo.name
                sharePosterBean.goodsName = goodsDetailBean.name
                sharePosterBean.goodsClass = goodsDetailBean.cname
                sharePosterBean.goodsPrice = AmountUtil.changeF2Y(getDefFansPrice(goodsDetailBean).toString())
                if (goodsDetailBean.seckillActProductExtDTO.checkNotNull()) {//秒杀商品
                    sharePosterBean.seckillPrice = AmountUtil.changeF2Y(goodsDetailBean.seckillActProductExtDTO?.fansPrice.toString())
                }
                val bundle1 = Bundle()
                bundle1.putSerializable(Constants.SHARE_POSTER_BEAN, sharePosterBean)
                ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SHARE_POSTER, bundle1)
            }
        })
    }


    val scrollList: ArrayList<View> = arrayListOf()

    /**
     * 是否有正在播放中的视频
     */
    fun isPaying(coverVpAdapter: GoodsCoverVpAdapter?): Boolean {
        if (coverVpAdapter?.goodsVideoView?.isPlay == true) {
            return true
        }
        return false
    }

    fun stopPlay(adapter: GoodsDetailAdapter) {
        adapter.coverVpAdapter?.goodsVideoView?.stopPlay()
    }

    fun addCartAnimation(llRootView: View, goodsDetailImageView: View, mAction_buy_car: View, context: Context) {

        //计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        val parentLoc = IntArray(2)
        llRootView.getLocationInWindow(parentLoc)

        //得到商品图片的坐标（用于计算动画开始的坐标）（此图片控件添加到根布局，居中）
        val startLoc = IntArray(2)
        goodsDetailImageView.getLocationInWindow(startLoc)

        //购物车控件的坐标(用于计算动画结束后的坐标)
        val endLoc = IntArray(2)
        mAction_buy_car.getLocationInWindow(endLoc)
        val startX = (startLoc[0] - parentLoc[0] + goodsDetailImageView.width / 2).toFloat()
        val startY = (startLoc[1] - parentLoc[1] + goodsDetailImageView.height / 2).toFloat()

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        val toX = (endLoc[0] - parentLoc[0] + mAction_buy_car.width / 2).toFloat()
        val toY = (endLoc[1] - parentLoc[1] + mAction_buy_car.height * 2 / 5).toFloat()

        //透明度和缩放动画，动画持续时间和动画透明度可以自己根据想要的效果调整
        val alphaAnimation: AlphaAnimation = AlphaAnimation(0f, 1f)
        alphaAnimation.duration = 280
        val scaleAnimation = ScaleAnimation(1f, 0.1f, 1f, 0.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        scaleAnimation.duration = 300

        //平移动画X轴 计算X轴要平移的距离，设置动画的偏移时间由透明度和缩放动画持续时间决定
        val translateAnimationX = TranslateAnimation(0f, toX - startX, 0f, 0f)
        translateAnimationX.startOffset = 300
        translateAnimationX.duration = 700
        //设置线性插值器
        translateAnimationX.interpolator = LinearInterpolator()

        //平移动画Y轴 同X轴
        val translateAnimationY = TranslateAnimation(0f, 0f, 0f, toY - startY)
        translateAnimationY.startOffset = 300
        translateAnimationY.duration = 700
        //设置加速插值器
        translateAnimationY.interpolator = AccelerateInterpolator()


        //动画集合
        val set = AnimationSet(false)
        set.addAnimation(alphaAnimation)
        set.addAnimation(scaleAnimation)
        set.addAnimation(translateAnimationX)
        set.addAnimation(translateAnimationY)
        set.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {
                goodsDetailImageView.visibility = View.VISIBLE
            }

            override fun onAnimationEnd(animation: Animation) {
                //动画执行完成
                goodsDetailImageView.visibility = View.INVISIBLE
                goodsDetailImageView.clearAnimation()
                set.cancel()
                animation.cancel()
                //购物车商品数量更新
                // TODO: 2022/9/6 数量+1
                //购物车控件 开始一个放大动画
                val scaleAnim = AnimationUtils.loadAnimation(context, R.anim.shop_car_scale)
                mAction_buy_car.startAnimation(scaleAnim)
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        //设置动画播放完以后消失，终止填充
        set.fillAfter = false
        goodsDetailImageView.startAnimation(set)
    }

}